import { defineStore } from 'pinia'
import { constantRoutes } from '@/router'
import cache from '@/plugins/cache'

const usePermissionStore = defineStore('permission', {
  state: () => ({
    routes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: [],
    commonlyUsedRoutes: [] // 常用菜单列表
  }),
  actions: {
    generateRoutes() {
      return new Promise((resolve) => {
        // 使用本地 constantRoutes 作为静态菜单
        this.routes = constantRoutes
        this.defaultRoutes = constantRoutes
        this.sidebarRouters = constantRoutes
        this.topbarRouters = constantRoutes
        this.setCommonlyUsedRoutes()  // 从 localStorage 恢复常用菜单
        resolve(constantRoutes)
      })
    },
    // 设置常用路由（从缓存读取）
    setCommonlyUsedRoutes() {
      const localList = cache.local.getJSON('commonlyUseMenu') || []
      this.commonlyUsedRoutes = localList
    },
    // 移除常用菜单项
    removeCommonlyUsedRoutes(item) {
      const index = this.commonlyUsedRoutes.findIndex((v) => v.path === item.path)
      if (index !== -1) {
        this.commonlyUsedRoutes.splice(index, 1)
        cache.local.setJSON('commonlyUseMenu', this.commonlyUsedRoutes)
      }
    },
    // 可选：添加常用菜单
    addCommonlyUsedRoute(route) {
      const exists = this.commonlyUsedRoutes.some((v) => v.path === route.path)
      if (!exists) {
        this.commonlyUsedRoutes.push(route)
        cache.local.setJSON('commonlyUseMenu', this.commonlyUsedRoutes)
      }
    }
  }
})

export default usePermissionStore
